#import "URLLoadingOperation.h"
#import "IDominoAppDelegate.h"
#import "PersonalContactXMLReader.h"
#import "DirectoryContactXMLReader.h"
@implementation URLLoadingOperation


- (id)initWithMailArray:(NSArray*)newArray mailBox:(NSString*)newMailBox
{
//Loading mails in mail boxes in background.
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	if(![super init])
		return nil;
	mailArray=[newArray retain];
	mailBox=[newMailBox retain];
	operationType=1;
	transactionDescription=[NSString stringWithFormat:@"%@%@%@", NSLocalizedString(@"PreloadingPrefix", @""),
							NSLocalizedString(mailBox, @""),NSLocalizedString(@"PreloadingSuffix", @"")] ;
	[appDelegate.transactionViewController addToTransaction:transactionDescription];

	return self;
}


- (id)initWithType:(int)type URL:(NSURL*)URL data:(NSData*)data description:(NSString*)description fromDatabase:(BOOL)isDatabase
{//type = 2 send mail,  type = 3 delete mail, type = 6 syncronize read flag
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	if(![super init])
		return nil;
	targetURL=[URL retain];
	postData=[data retain];
	operationType=type;
	if(type==2){
		transactionDescription=description;
	}else if(type==3){
		transactionDescription=description;
	}else if(type==6){
		transactionDescription=@"";
	}
	if(!isDatabase)
		[appDelegate.databaseInteraction saveOperationToDatabase:URL type:type data:data description:description];
	if(type!=6)
		[appDelegate.transactionViewController addToTransaction:transactionDescription];
	return self;
}


- (id)initWithType:(int)type
{//update personal or directory contacts
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	if(![super init])
		return nil;
	operationType=type;
	if(operationType==4)
		transactionDescription=NSLocalizedString(@"UpdatePersonalTransaction", @"");
	else if(operationType==5)
		transactionDescription=NSLocalizedString(@"UpdateDirectoryTransaction", @"");
	[appDelegate.transactionViewController addToTransaction:transactionDescription];
	return self;
}

- (void)dealloc
{
	if(operationType==1){
		[mailArray release];
		[mailBox release];
	}else if (operationType==2 || operationType==3 || operationType==6){
		[targetURL release];
		[postData release];
		[transactionDescription release];
	}
	[super dealloc];
}

- (void)main{

	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	if(![appDelegate isDataSourceAvailable]){
		
		return;
	}
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if(operationType==1){//preloading mail, don't need backup
		for(int i=0;i<[mailArray count];i++)
		{
			Mail* mail=[mailArray objectAtIndex:i];			
			if(![mail hasContentDownloaded]){
				NSURL* fetchMailContentUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($%@)/%@/?OpenDocument&Form=m_MailReplyEdit&PresetFields=ParentUNID;%@,s_NoMarkRead;1", 	appDelegate._serverName, 
									appDelegate._mailServer,appDelegate._databaseName, mailBox, [mail UNID], [mail UNID]]];
				NSString* all=[appDelegate sendHttpRequest:fetchMailContentUrl isPost:NO postData:nil];	;
				NSRange range=[all rangeOfString:@"<textarea class=\"memoComposeField memoFieldText\" id=\"msgBody\" name=\"Body\">"];
				if(range.location!=NSNotFound){
					NSRange range1=[all rangeOfString:@"</textarea>"];
					if(range1.location!=NSNotFound){
						all=[all substringToIndex:range1.location];
						NSString* toString=[all substringFromIndex:[all rangeOfString:@"To:"].location+3];
						toString=[toString substringToIndex:[toString rangeOfString:@"\n"].location];
						NSString* fromString=[all substringFromIndex:[all rangeOfString:@"From:"].location+5];
						fromString=[fromString substringToIndex:[fromString rangeOfString:@"\n"].location];
						NSString* content=[all substringFromIndex:[all rangeOfString:@"=======================" options:NSBackwardsSearch].location+24 ]; 
						while([content hasPrefix:@"\n"])
							content=[content substringFromIndex:1];
						NSMutableString* content1=[NSMutableString stringWithString:content];
						//temp replace, need improvement
						[content1 replaceOccurrencesOfString:@"&quot;" withString:@"\"" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
						[content1 replaceOccurrencesOfString:@"&amp;" withString:@"&" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
						[content1 replaceOccurrencesOfString:@"&lt;" withString:@"<" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
						[content1 replaceOccurrencesOfString:@"&gt;" withString:@">" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
						if([mail hasAttachment]){
							range=[content1 rangeOfString:@"[attachment(s) \""];
							if(range.location!=NSNotFound){
								NSString* attachmentName=[content1 substringFromIndex:range.location+range.length];
								attachmentName=[attachmentName substringToIndex:[attachmentName rangeOfString:@"\""].location];	
								[mail setAttachmentName:attachmentName];
								int size=([[mail size] intValue]/1024);
								content1=[NSString stringWithFormat:@"%@Attachment:%@ %dKB", [content1 substringToIndex:range.location], attachmentName,size];
							}
						}
						[mail setFullSender:fromString];
						[mail setReceiver:toString];
						[mail setContent:content1];
						[mail markDownload];
					}
				}
				[appDelegate.mailListViewController setMailStatusBarWithMessage:[NSString stringWithFormat:
									@"%@%@%@: %d/%d",NSLocalizedString(@"PreloadingPrefix", @"Preloading"),
									 NSLocalizedString(mailBox, @""), NSLocalizedString(@"PreloadingSuffix", @"content"), i+1, [mailArray count]] animateIndicator:YES];
			}			
			//update UI here
		}
		[appDelegate savePreloadingMails:mailArray mailBox:mailBox];
		[appDelegate.transactionViewController removeFromTransaction:transactionDescription];
	}
	else if(operationType==2){//send mail, need backup
		[appDelegate sendHttpRequest:targetURL isPost:YES postData:postData];
		[appDelegate.databaseInteraction deleteOperationInDatabase:targetURL];
		[appDelegate.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"MailSend", @"Mail send") animateIndicator:NO];
		[appDelegate.transactionViewController shiftToHistoryTransaction:transactionDescription];
	}
	else if(operationType==3){//delete mail, need backup
		[appDelegate sendHttpRequest:targetURL isPost:YES postData:postData];
		[appDelegate.databaseInteraction deleteOperationInDatabase:targetURL];
		[appDelegate.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"MailDelete", @"Mail delete") animateIndicator:NO];
		[appDelegate.transactionViewController shiftToHistoryTransaction:transactionDescription];
	}
	else if(operationType==4){//update contacts, need backup
		[appDelegate.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"UpdatingPersonal", @"") animateIndicator:YES];
		NSURL *fetchContactUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($Contacts)?ReadViewEntries&count=1000", 	appDelegate._serverName, appDelegate. _mailServer,  appDelegate._databaseName]];
		NSString* a=[appDelegate sendHttpRequest:fetchContactUrl  isPost:NO  postData:nil];
		NSData* urlData=[a dataUsingEncoding:NSUTF8StringEncoding];
		PersonalContactXMLReader *streamingParser = [[PersonalContactXMLReader alloc] init];
		NSError *parseError = nil;
		NSArray* contactList=[streamingParser parseXMLFileFromData:urlData parseError:&parseError];
		[streamingParser release];   
		[appDelegate.databaseInteraction savePersonalContactsToDatabase:contactList];
		[appDelegate.contactListViewController initDisplayList];
		[appDelegate.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"PersonalContactUpdate", @"Personal Contact Updated!") animateIndicator:NO];
		[appDelegate.transactionViewController shiftToHistoryTransaction:transactionDescription];
	}
	else if(operationType==5){//update directory, need backup
		
		[appDelegate.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"UpdatingDirectory", @"") animateIndicator:YES];
		NSString* directoryContactsServer=appDelegate._mailServer;
		NSRange range=[directoryContactsServer rangeOfString:@"/"];
		if (range.location!=NSNotFound)
			directoryContactsServer=[directoryContactsServer substringToIndex:range.location];
		BOOL hasMoreEntries=YES;
		int startCount=0;
		NSArray* firstNameList;
		NSArray* lastNameList;
		NSArray* UNIDList;
		DirectoryContactXMLReader *streamingParser;
		NSData* urlData;
		NSURL *fetchContactUrl;
		NSError *parseError;
		NSArray* containerArray;
		[appDelegate.databaseInteraction resetDirectoryDatabase];
		while(hasMoreEntries){
			firstNameList=nil;
			lastNameList=nil;
			UNIDList=nil;
			fetchContactUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/directory/dcmobi.nsf/Users?ReadViewEntries&count=1000&start=%d",	appDelegate._serverName,directoryContactsServer, startCount]];
			NSString* content=[appDelegate sendHttpRequest:fetchContactUrl  isPost:NO  postData:nil] ;
			urlData=[content dataUsingEncoding:NSUTF8StringEncoding];
			streamingParser= [[DirectoryContactXMLReader alloc] init];
			parseError = nil;
			containerArray=[streamingParser parseXMLFileFromData:urlData parseError:&parseError];
			firstNameList=[containerArray objectAtIndex:0];
			lastNameList=[containerArray objectAtIndex:1];
			UNIDList=[containerArray objectAtIndex:2];
			if([firstNameList count]==0)
				hasMoreEntries=NO;
			[streamingParser release];   
			startCount+=1000;
			[appDelegate.databaseInteraction saveDirectoryContactsToDatabase:firstNameList lastName:lastNameList UNID:UNIDList];
			[appDelegate.mailListViewController setMailStatusBarWithMessage:[NSString stringWithFormat:@"%d %@", 
					 startCount, NSLocalizedString(@"DirectoryDownloadProcess", @"Directory Contacts Downloaded")] animateIndicator:YES];

		}
		[appDelegate.contactListViewController initDisplayList];
		[appDelegate.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"DirectoryContactUpdate", @"Directory Contacts Updated!") animateIndicator:NO];
		[appDelegate.transactionViewController shiftToHistoryTransaction:transactionDescription];
	}

	if(operationType==6){//delete mail, need backup
		[appDelegate sendHttpRequest:targetURL isPost:YES postData:postData];
		[appDelegate.databaseInteraction deleteOperationInDatabase:targetURL];
	}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;	
	[pool release];
}


@end
